﻿CREATE TRIGGER [tr_MenuEvent]
   ON [dbo].[t_MenuEvent]
FOR INSERT,UPDATE
AS 

IF @@ROWCOUNT = 0 RETURN
SET NOCOUNT ON

IF EXISTS(SELECT * FROM v_MenuEvent me INNER JOIN inserted i ON i.EventID = me.EventID WHERE(me.MenuFromID > 0) AND (me.MenuToID > 0) AND me.StatusNameSpace <> me.StatusNameSpaceTo) BEGIN
	ROLLBACK TRAN
	RAISERROR('MenuFrom and MenuTo must be from the same namespace',16,1)
	RETURN
END

IF NOT UPDATE(MenuFromID) AND NOT UPDATE(MenuToID) RETURN

IF EXISTS(SELECT * FROM inserted i INNER JOIN t_WorkFlow wf
					ON (i.MenuFromID IS NULL OR i.MenuFromID = wf.MenuID) AND
						 (i.MenuToID IS NULL OR i.MenuToID = wf.NextMenuID)
	 ) RETURN

ROLLBACK TRAN
RAISERROR('Menu must be a part of WorkFlow Path.',16,1)

